package com.auhaix.aspect;

import com.auhaix.common.UserException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.auhaix.Utils.StringUtils.getStringFormatValueOfObject;

/**
 * Author: Auhaix
 * E-mail: xh@qiandw.com
 * Description:日志切面，用于打印方法出入参及异常信息
 * CreatedTime: 2017/8/1 13:56
 * Modified by:
 */
@Aspect
@Component
public class LogAspect {
    @Autowired
    private ObjectMapper objectMapper;

    @Pointcut("execution(public * com.auhaix.controller.UserController.*(..))")
    public void pointcuts() {
    }

    @Around("pointcuts()")
    public Object log(ProceedingJoinPoint proceedingJoinPoint) {
        Logger logger = LoggerFactory.getLogger(proceedingJoinPoint.getTarget().getClass());
        Object response = null;
        try {
            String methodName = proceedingJoinPoint.getSignature().getDeclaringTypeName() + "." + proceedingJoinPoint.getSignature().getName();
            //进入类方法
            logger.info("Enter method({})", methodName);
            //入参Args
            Integer count = proceedingJoinPoint.getArgs().length;
            if (count > 0) {
                for (int i = 0; i < count; i++) {
                    Object o = proceedingJoinPoint.getArgs()[i];
                    //logger.info(o.getClass().getName());
                    logger.info("Parameters(Args[{}]->{})", i, getStringFormatValueOfObject(objectMapper, o));
                }
            }
            response = proceedingJoinPoint.proceed();
            //返回参数
            logger.info("Return({})", response);
            //退出
            logger.info("Exit method({})", methodName);
        } catch (Throwable throwable) {
            //异常信息
            if (throwable instanceof UserException) {//自定义异常
                UserException userException = (UserException) throwable;
                logger.error("UserException(msgCode->{},msg->{})", userException.getMsgCode(), userException.getMessage());
            } else {//其他异常
                logger.error("Execute error({})", throwable.getMessage());
            }
        }
        return response;
    }

}
